package com.jaws.core.common.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.parameternameprovider.ParanamerParameterNameProvider;

import com.jaws.core.common.util.DataUtil;

/**
 * 
 * 手机号验证器
 * @author lixin
 * @date 2018-04-24 15:11:47
 * @since v1.0.0
 */
public class MobileNoValidator implements ConstraintValidator<MobileNoValid, String> {

	private Validator validator;

	private MobileNoValid annotation;

	@Override
	public void initialize(MobileNoValid constraintAnnotation) {
		annotation = constraintAnnotation;
	}

	public MobileNoValidator() {
		if (validator == null) {
			ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure().failFast(true).parameterNameProvider(new ParanamerParameterNameProvider())
					.buildValidatorFactory();
			validator = validatorFactory.getValidator();
		}
	}

	@Override
	public boolean isValid(final String str, final ConstraintValidatorContext context) {
		StringBuilder msg = new StringBuilder(annotation.message());
		if(StringUtils.isBlank(str)){
			return true;
		}
		if (!DataUtil.isMobile(str.trim())) {
			context.buildConstraintViolationWithTemplate(msg.toString()).addConstraintViolation();
			return false;
		}
		return true;
	}

}
